<template>
  <div class="home-center-container">
    <div class="home-center-tabs">
      <div class="home-center-tab">{{currentContent.name?currentContent.name:""}}</div>
    </div>
    <div class="contents">
      <div v-if="currentContent.dialogType === 'image'" class="content-images">
        <div class="image-item" v-for="(img, index) in currentContent.dialogData.images" :key="index">
<!--          <img class="img" :src="img.url" :alt="currentContent.dialogData.title" />-->
          <el-image
                  style="width: 100%; height: 100%"
                  :src="img.url"
                  z-index="100"
                  :preview-src-list="currentContent.dialogData.images.map(v => v.url)"
                  :initial-index="index"
                  :fit="'cover'">
          </el-image>
          <div class="species-name">{{img.name}}</div> <!-- 示例名称 -->
        </div>
      </div>
      <div v-else-if="currentContent.dialogType === 'audio'" class="content-audios">
        <div class="audio-card" :id="'card1'" @click="playAudio(0)" v-if="currentContent.dialogData.audios && currentContent.dialogData.audios.length > 0">
          <img :src="currentContent.dialogData.audios[0].img"
               @error="showDefaultImg"
               :alt="currentContent.dialogData.audios[0].name" class="audio-image">
          <div class="audio-content">
            <div class="audio-info">
              <h3>{{currentContent.dialogData.audios[0].name}}</h3>
              <div class="time-display" id="time1">0:00 / 0:00</div>
            </div>
            <div class="waveform-container">
              <div class="waveform" ref="waveform1" id="waveform1"></div>
              <div class="progress-bar" id="progress1"></div>
            </div>
          </div>
        </div>
        <div class="audio-card" :id="'card2'" v-if="currentContent.dialogData.audios && currentContent.dialogData.audios.length > 1">
          <img :src="currentContent.dialogData.audios[1].img"
               @error="showDefaultImg"
               :alt="currentContent.dialogData.audios[1].name" class="audio-image" @click="playAudio(1)">
          <div class="audio-content">
            <div class="audio-info">
              <h3>{{currentContent.dialogData.audios[1].name}}</h3>
              <div class="time-display" id="time2">0:00 / 0:00</div>
            </div>
            <div class="waveform-container">
              <div class="waveform" ref="waveform2" id="waveform2"></div>
              <div class="progress-bar" id="progress2"></div>
            </div>
          </div>
        </div>
        <div class="audio-card" :id="'card3'" @click="playAudio(2)" v-if="currentContent.dialogData.audios && currentContent.dialogData.audios.length > 2">
          <img :src="currentContent.dialogData.audios[2].img"
               @error="showDefaultImg"
               :alt="currentContent.dialogData.audios[2].name"
               class="audio-image">
          <div class="audio-content">
            <div class="audio-info">
              <h3>{{currentContent.dialogData.audios[2].name}}</h3>
              <div class="time-display" id="time3">0:00 / 0:00</div>
            </div>
            <div class="waveform-container">
              <div class="waveform" ref="waveform3" id="waveform3"></div>
              <div class="progress-bar" id="progress3"></div>
            </div>
          </div>
        </div>
      </div>
      <!-- 视频类型 -->
      <div v-else-if="currentContent.dialogType === 'video'" class="content-video">
        <div class="video-grid">
          <div class="video-item" v-for="(video, index) in currentContent.dialogData.videos" :key="index">
            <video class="hide-progress-bar"
                   :ref="'videoPlayer' + index"
                   controls="false" autoplay loop
                   :src="video.url"
                   controlsList="nodownload"
                   preload="auto"
            >
              您的浏览器不支持 video 标签。
            </video>
          </div>
        </div>
      </div>
      <!-- 图表类型 -->
      <div v-else-if="currentContent.dialogType === 'chart'" ref="trendChart" class="content-chart"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import WaveSurfer from "wavesurfer.js"
export default {
  name: 'HomeCenter',
  props: {
    currentContent: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      color:['#3B7EFF','#00FFE3','#9890FF','#50C32D','#B38611','#DBAF86','#3B7EFF','#00FFE3'],
      wavesurfers: [],
      currentAudioIndex: 0,
      isPlaying: false,
      autoplayAttempted: false,
      cards: [],
      timeDisplays: [],
      trendChart: null,
      isFirstLoad: true,
      bird:require(`@/assets/img/bird.png`)
    }
  },
  watch: {
    currentContent: {
      handler(newVal) {
        if (newVal) {
          this.cleanupResources();
          switch (newVal.name) {
            case '红外':
            case '视频':
              this.$nextTick(() => {
                setTimeout(() => {
                  this.initVideoPlayers();
                  this.playAllVideos();
                }, 500);
              });
              break;
            case '声纹':
              this.$nextTick(() => {
                setTimeout(() => {
                  this.initWaveSurfers();
                  this.loadAudio(0);
                  this.attemptAutoplay(0);
                }, 1200);
              });
              break;
            case '虫情':
              // 虫情设备使用图片类型，不需要特殊初始化
              break;
            case '气象':
            case '土壤':
              // 确保在DOM更新后初始化图表
              this.$nextTick(() => {
                setTimeout(() => {
                  if (newVal.dialogType === 'chart') {
                    this.initTrendChart(newVal.dialogData);
                  }
                }, 1000);
              });
              break;
            case '空气质量':
              // 确保在DOM更新后初始化图表
              this.$nextTick(() => {
                setTimeout(() => {
                  if (newVal.dialogType === 'chart') {
                    this.initTrendChart(newVal.dialogData);
                  }
                }, 1000);
              });
              break;
          }
        }
      },
      immediate: true
    }
  },
  methods: {
    showDefaultImg(event){
      event.target.src = require(`@/assets/img/bird.png`);
    },
    cleanupResources() {
      // 清理视频播放器
      if (this.videoPlayer) {
        this.videoPlayer.pause();
        this.videoPlayer.src = '';
        this.videoPlayer.load();
      }

      // 清理音频播放器
      while (this.wavesurfers.length>0){
        this.wavesurfers[0].stop();
        this.wavesurfers[0].destroy();
        this.wavesurfers.pop();
      }

      // 清理图表
      if (this.trendChart) {
        this.trendChart.dispose();
        this.trendChart = null;
      }

      this.currentVideoIndex = 0;
      this.currentAudioIndex = 0;
      this.currentImageIndex = 0;
      this.isPlaying = false;
      this.currentTime = '00:00';
      this.duration = '00:00';
    },
    initTrendChart(data) {
      try {
        if (this.trendChart) {
          this.trendChart.dispose();
          this.trendChart = null;
        }

        const chartDom = this.$refs.trendChart;

        this.trendChart = echarts.init(chartDom);
        let select={};
        let series = [];
        let y = [];
        for (let i = 0; i < data.yDatas.length; i++) {
          series.push({
            name: data.legends[i],
            data: data.yDatas[i],
            yAxisIndex: i,
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              color: this.color[i%8],
              width: 2
            },
            // itemStyle: {
            //   color: '#00FFFF',
            //   borderWidth: 2,
            //   borderColor: '#fff'
            // },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(0, 255, 255, 0.3)' },
                { offset: 1, color: 'rgba(0, 255, 255, 0.1)' }
              ])
            }
          });
          y.push(  {
            type: 'value',
            scale: true,
            position: i==0?'left':'right',
            offset: i>1?30*(i-1):0,  // 偏移量，避免重叠
            splitLine: i==0?{
              lineStyle: {
                color: 'rgba(255, 255, 255, 0.1)'
              }
            }:{show: false},
            axisLine: {
              show: false
            },
            axisLabel: {
              color: this.color[i%8]
            }
          });
          select[data.legends[i]]=i<2?true:false;
        }

        const option = {
          backgroundColor: 'transparent',
          grid: {
            left: '5%',
            right: '5%',
            top: '10%',
            bottom: '10%',
            containLabel: true
          },
          legend: {
            data: data.title?data.title:data.legends,
            selected:select,
            textStyle: {
              color: '#ccc', // 未选中时的字体颜色
            },
            inactiveColor: '#333', // 被禁用时的字体颜色
          },
          tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(0,24,106,0.8)',
            borderColor: 'rgba(0,150,255,0.3)',
            textStyle: {
              color: '#fff'
            }
          },
          xAxis: {
            type: 'category',
            data: data.xDatas,
            axisLine: {
              lineStyle: {
                color: 'rgba(255, 255, 255, 0.3)'
              }
            },
            axisLabel: {
              color: '#fff'
            }
          },
          yAxis: y,
          series: series
        };

        this.trendChart.setOption(option);

        window.addEventListener('resize', this.handleChartResize);
      } catch (error) {
        console.error('Error initializing trend chart:', error);
      }
    },

    handleChartResize() {
      if (this.trendChart) {
        this.trendChart.resize();
      }
    },
    initWaveSurfers() {
      try {
        this.wavesurfers = []
        this.currentAudioIndex = 0
        this.isPlaying = false
        this.autoplayAttempted = false

        const waveform = [
          this.$refs.waveform1,
          this.$refs.waveform2,
          this.$refs.waveform3
        ]

        if (!waveform.every(container => container)) {
          console.warn('Some waveform containers are not found')
          return
        }

        this.cards = [
          document.getElementById('card1'),
          document.getElementById('card2'),
          document.getElementById('card3')
        ]

        this.timeDisplays = [
          document.getElementById('time1'),
          document.getElementById('time2'),
          document.getElementById('time3')
        ]

        for (let i = 0; i < 3; i++) {
          const wavesurfer = WaveSurfer.create({
            container: waveform[i],
            waveColor: '#4a90e2',
            progressColor: '#2c3e50',
            cursorColor: '#e74c3c',
            barWidth: 1,
            barRadius: 2,
            cursorWidth: 1,
            height: 50,
            barGap: 1,
            responsive: true,
            normalize: true,
            interact: false
          })

          wavesurfer.on('error', function(error) {
            // console.error('WaveSurfer错误:', error)
          })

          wavesurfer.load(this.currentContent.dialogData.audios[i].url)

          wavesurfer.on('ready', () => {
            this.updateTimeDisplay(i, 0, wavesurfer.getDuration())

            if (i === 0 && !this.autoplayAttempted) {
              this.autoplayAttempted = true
              this.loadAudio(0)
              setTimeout(() => {
                this.attemptAutoplay(0)
              }, 2000)
            }
          })

          wavesurfer.on('audioprocess', () => {
            this.updateTimeDisplay(i, this.wavesurfers[i].getCurrentTime(), this.wavesurfers[i].getDuration())
            this.updateProgressBar(i, this.wavesurfers[i].getCurrentTime() / this.wavesurfers[i].getDuration())
          })

          wavesurfer.on('finish', () => {
            this.playNextAudio()
          })

          this.wavesurfers.push(wavesurfer)
        }
      } catch (error) {
        // console.error('Error initializing wave surfers:', error)
      }
    },
    initVideoPlayers() {
      try {
        // 使用正确的选择器获取所有video元素
        const videoPlayers = document.querySelectorAll('.video-item video');
        if (videoPlayers && videoPlayers.length > 0) {
          videoPlayers.forEach(player => {
            if (player) {
              player.play().catch(error => {
                // console.error('Error playing video:', error)
              })
            }
          })
        }
      } catch (error) {
        // console.error('Error initializing video players:', error)
      }
    },
    loadAudio(index) {
      if (!this.wavesurfers[index]) return
      if (!this.wavesurfers[index]) return
      for (let i = 0; i < this.wavesurfers.length; i++) {
        this.wavesurfers[i].stop()
      }
      this.currentAudioIndex = index

      this.cards.forEach((card, i) => {
        card.classList.remove('active')
      })
      this.cards[index].classList.add('active')
    },
    attemptAutoplay(index) {
      const playPromise = this.wavesurfers[index].play()

      if (playPromise !== undefined) {
        playPromise.then(() => {
          this.isPlaying = true
          this.currentAudioIndex = index
        })
                .catch(error => {
                  // console.log('自动播放被阻止:', error)
                })
      }
    },
    updateActiveCard(index) {
      this.cards.forEach((card, i) => {
        card.classList.remove('active')
      })
      this.cards[index].classList.add('active')
    },
    playAudio(index) {
      if (index === this.currentAudioIndex && this.isPlaying) return

      if (this.isPlaying) {
        this.wavesurfers[this.currentAudioIndex].stop()
      }

      this.currentAudioIndex = index
      const playPromise = this.wavesurfers[index].play()

      if (playPromise !== undefined) {
        playPromise.then(() => {
          this.isPlaying = true
          this.updateActiveCard(index)
        })
                .catch(error => {
                  // console.error('播放失败:', error)
                })
      }
    },
    playNextAudio() {
      const nextIndex = (this.currentAudioIndex + 1) % 3
      setTimeout(() => {
        this.playAudio(nextIndex)
      }, 3000)
    },
    updateTimeDisplay(index, currentTime, duration) {
      if (this.timeDisplays[index]) {
        this.timeDisplays[index].textContent = `${this.formatTime(currentTime)} / ${this.formatTime(duration)}`
      }
    },
    updateProgressBar(index, progress) {
      const progressBar = document.getElementById(`progress${index+1}`)
      if(progressBar) {
        progressBar.style.width = `${progress * 100}%`
      }
    },
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${minutes}:${secs < 10 ? '0' : ''}${secs}`
    },
    handleVideoError(event) {
      console.error('视频加载失败', event)
    },
    playAllVideos() {
      try {
        // 获取所有视频元素
        const videoElements = document.querySelectorAll('.video-item video');
        if (videoElements && videoElements.length > 0) {
          videoElements.forEach(video => {
            // 设置视频为静音，这样可以绕过大多数浏览器的自动播放限制
            video.muted = true;

            // 尝试播放视频
            const playPromise = video.play();
            if (playPromise !== undefined) {
              playPromise.catch(error => {
                console.warn('自动播放被阻止，等待用户交互:', error);

                // 添加点击事件监听器到整个文档
                const playHandler = () => {
                  // 尝试播放所有视频
                  videoElements.forEach(v => {
                    v.muted = false; // 取消静音
                    v.play().catch(e => {
                      console.error('播放失败:', e);
                    });
                  });

                  // 移除事件监听器
                  document.removeEventListener('click', playHandler);
                  document.removeEventListener('touchstart', playHandler);
                };

                // 添加点击和触摸事件监听器
                document.addEventListener('click', playHandler);
                document.addEventListener('touchstart', playHandler);

                // 显示提示信息
                const videoContainer = video.closest('.video-item');
                if (videoContainer) {
                  const playButton = document.createElement('div');
                  playButton.className = 'video-play-button';
                  playButton.innerHTML = '<span>点击页面任意位置播放视频</span>';
                  videoContainer.appendChild(playButton);
                }
              });
            }
          });
        } else {
          console.warn('No video elements found');
        }
      } catch (error) {
        console.error('Error playing videos:', error);
      }
    }
  },
  beforeDestroy() {
    // 清理视频
    if (this.$refs.videoPlayer) {
      const videoPlayers = this.$refs.videoPlayer;
      if (Array.isArray(videoPlayers)) {
        videoPlayers.forEach(player => {
          if (player) player.pause();
        });
      }
    }
    // 清理图表
    if (this.trendChart) {
      this.trendChart.dispose();
      this.trendChart = null;
    }
    // 清理设备图表
    // this.deviceCharts.forEach(chart => {
    //   chart && chart.dispose();
    // });

    // 清理音频播放器
    while (this.wavesurfers.length>0){
      this.wavesurfers[0].stop();
      this.wavesurfers[0].destroy();
      this.wavesurfers.pop();
    }
    window.removeEventListener('resize', this.handleResize);

    // Clean up monitor chart
    if (this.monitorChart) {
      this.monitorChart.dispose()
      this.monitorChart = null
    }
    if (this.handleMonitorChartResize) {
      window.removeEventListener('resize', this.handleMonitorChartResize)
    }
    if (this.airQualityChart) {
      this.airQualityChart.dispose();
      this.airQualityChart = null;
    }

  }
}
</script>

<style lang="scss" scoped>
.content-chart {
  height: 240px;
  width: 100%;
}
.home-center-container{
  width: 100%;
  position: absolute;
  bottom: 20px;
}
.contents{
  width: 95%;
  background-color: #063C6A;
  border-radius:10px;
  margin-left: 10px;
  margin-right: 10px;
  padding: 10px;
  z-index: 200;
  pointer-events: auto;
}
.home-center-tabs {
  display: flex;
  align-items: flex-end;
  height: 40px;
  width: 100%;
  background-size: 504px 40px;
  background-repeat: no-repeat;
  background-position: 0 0;
  pointer-events: auto;
  position: relative;
  top: 5px;
  left: 10px;
}

.home-center-tab {
  width: 190px;
  height: 40px; 
  line-height: 40px;
  color: #fff;
  font-size: 18px;
  cursor: pointer;
  transition: color 0.2s;
  background:url('@/assets/img/home-center-4.png') no-repeat 0 center;
  padding-left: 30px;
}

.content-audios {
  display: flex;
  gap: 25px;
  justify-content: center;
  align-items: center;
  /*height: 281px;*/
  height: 100%;
  position: relative;
  /*top: 10px;*/
  /*bottom: 10px;*/

  /*margin-top: 50px;*/
  /*margin-bottom: 10px;*/
}

.audio-cards {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  gap: 10px;
}

.audio-card {
  width: 30%;
  overflow: hidden;
  box-shadow: 0 6px 12px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
  background-color: white;
  position: relative;
  cursor: pointer;
  display: flex;
  flex-direction: column;
}

.audio-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0,0,0,0.15);
}

.audio-card.active {
  box-shadow: 0 0 0 3px #4a90e2, 0 10px 20px rgba(74, 144, 226, 0.3);
}

.audio-card.active::after {
  content: "正在播放";
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #4a90e2;
  color: white;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.audio-image {
  width: 100%;
  height: 150px;
  object-fit: fill;
}

.audio-content {
  height: 50px;
  display: flex;
  flex: 1;
  padding: 5px;
}

.audio-info {
  flex: 1;
  padding-right: 5px;
}

.audio-info h3 {
  padding-top: 5px;
  padding-left: 5px;
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 12px;
  height: 18px;
}

.audio-info p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.waveform-container {
  width: 65%;
  height: 50px;
  background-color: #f1f3f4;
  border-radius: 6px;
  position: relative;
  overflow: hidden;
}

.waveform {
  width: 100%;
  height: 100%;
}

.progress-bar {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 0;
  background-color: rgba(74, 144, 226, 0.2);
  pointer-events: none;
}

.time-display {
  padding-left: 5px;
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 5px;
  text-align: left;
}

.autoplay-message {
  text-align: center;
  color: #e74c3c;
  margin-bottom: 20px;
  font-size: 14px;
  display: none;
}

@media (max-width: 900px) {
  .audio-cards {
    flex-direction: column;
  }

  .audio-card {
    width: 100%;
    margin-bottom: 20px;
  }

  .waveform-container {
    width: 120px;
  }
}
.content-images {
  display: flex;
  gap: 20px;
  justify-content: center;
  align-items: center;
  /*height: 260px;*/
  position: relative;
  /*top: 0px;*/
  .image-item {
    position: relative;
    flex: 0 1 31%;
    height: 220px;
    background: rgba(0, 24, 106, 0.5);
    border: 1px solid rgba(0, 150, 255, 0.3);
    border-radius: 4px;
    overflow: hidden;
    .species-name {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      z-index: 1000;
      background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
      color: white;
      text-align: center;
      padding: 4px 0;
      font-size: 12px;
      font-family: Arial, sans-serif;
    }
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}

.content-video {
  height: 200px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  z-index: 1000;
  .video-grid {
    display: flex;
    gap: 10px;
    width: 100%;
    height: 100%;
    padding: 10px;
    overflow: hidden;
  }

  .video-item {
    flex: 1;
    height: 100%;
    /*padding-top: 20px;*/
    video {
      width: 100%;
      height: 100%;
      object-fit: fill;
    }
  }
}

.content-chart {
  height: 240px;
  width: 100%;
  padding-top: 30px;
  display: flex;
  justify-content: center;
  position: relative;
  z-index: 100;
}
</style>
